package lyc.springcloud.admin.service.impl;

import lombok.extern.slf4j.Slf4j;
import lyc.springcloud.admin.dao.IndexDao;
import lyc.springcloud.admin.service.def.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class IndexServiceImpl implements IndexService {
    @Autowired
    private IndexDao indexDao;

    @Override
    public List<Map> selectMenuTreeById(String params) {
        String root_id = "root_node";
        // 查询所有菜单类资源---平铺数据
        List<Map> allMenuList = indexDao.selectAllMenuTree();
        // 查询用户拥有的菜单类资源---平铺数据(包括自己的资源和父级资源)
        List<String> userHasMenuList = indexDao.userHasMenuList(params); // 查询自己拥有的资源
        List<String> userHasParentResourceList = indexDao.userHasParentResourceList(params); // 查询拥有的父级资源
        userHasMenuList.addAll(userHasParentResourceList);

        // 一级菜单---平铺数据
        List<Map> all_level1_menuList = new ArrayList<Map>();
        List<Map> menuTreeList = new ArrayList<Map>();
        // 搞定一级菜单(menu不需要展示root级的菜单，进来只看到收起的所有一级菜单)
        for (Map item : allMenuList) {
            String parentId = (String) item.get("parentId");
            String resourceId = (String) item.get("resourceId");
            if (parentId.equals(root_id) && userHasMenuList.contains(resourceId)) {
                all_level1_menuList.add(item);
            }
        }
        // 一级菜单---加children属性
        for (Map item : all_level1_menuList) {
            item.put("children", getRestNode((String) item.get("resourceId"), allMenuList, userHasMenuList));
    }

        // 生成menuTree菜单
        menuTreeList.addAll(all_level1_menuList);
        return menuTreeList;
    }

    private List<Map> getRestNode(String parentId, List<Map> allMenuList, List<String> userHasMenuList) {
        // 也许这种递归写法可以支持n级的tree分支，但前端的iview组件menu多一级就要多写一层dom，目前3级
        List<Map> restNodeList = new ArrayList<Map>();
        for (Map item : allMenuList) {
            String pId = (String) item.get("parentId");
            String resourceId = (String) item.get("resourceId");
            if(pId.equals(parentId) && userHasMenuList.contains(resourceId)) {
                restNodeList.add(item);
            }
        }
        for(Map item : restNodeList) {
            String pId = (String) item.get("parentId");
            item.put("children", getRestNode((String) item.get("resourceId"), allMenuList, userHasMenuList));
        }
        // 递归退出条件
        if (restNodeList.size() == 0) {
            return null;
        }
        return restNodeList;
    }
}
